<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017-11-16
 * Time: 9:32
 */

namespace App\Http\Biz;


use App\Http\Model\PtGoods;
use App\Http\Model\PtGoodsOrderMid;
use App\Http\Model\PtGoodsSpec;
use App\Http\Model\PtSuppGoodsGroup;
use App\Http\Model\ShopGoodsGroupMid;
use App\Http\Model\Supp;
use App\Http\Utils\Common\Consts;
use App\Http\Utils\Common\DictUtils;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Monolog\Formatter\LogglyFormatter;
use Monolog\Handler\LogglyHandler;

class SuppGoodsBiz
{


    //根据条件获取商品列表
    public function readGoodsByCondition($supp_id,$goods_name,$group_id,$status){
        try {
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'start');
            $ptGoods=PtGoods::query();
            $ptGoods->where('creator_ownto_id',$supp_id);
            if(!empty($goods_name)){
                $ptGoods->where('goods_name', 'like', '%'.$goods_name.'%');
            }
            if(!empty($group_id)){//根据分组查询商品列表
                //根据分组ID查询这个分组下面的所有商品
                $goods_ids=PtGoods::where('creator_ownto_id',$supp_id)->pluck('id')->all();
                $ids=array();
                $group_goods_ids=ShopGoodsGroupMid::where('group_id',$group_id)->pluck('goods_id')->all();
                if($group_goods_ids!=null&&count($group_goods_ids)>0){
                    foreach ($group_goods_ids as $gid){
                        if(in_array($gid,$goods_ids)){
                            $ids[]=$gid;
                        }
                    }
                }
                if($ids!=null&&count($ids)>0){
                    $ptGoods->whereIn('id',$ids);
                }else{
                    return null;
                }
            }
            if(!empty($status)){
                //status商品状态:1，出售中；上线的，并且库存数量不为零的 2，售罄的；上线的，并且库存数量为零的 3，仓库中；下线的
                switch ($status){
                    case 1:
                        $ptGoods->where('online',0)->where('total_stock_num','>',0);
                        break;
                    case 2:
                        $ptGoods->where('online',0)->where('total_stock_num','=',0);
                        break;
                    case 3:
                        $ptGoods->where('online',1);
                        break;
                    default:
                        break;
                }
            }else{
                $ptGoods->where('online',0)->where('total_stock_num','>',0);
            }

            $result=$ptGoods->orderBy('id','desc')->select('id','goods_name','goods_img','total_stock_num')->paginate(Consts::PAGE_SIZE);
            if(!empty($result)){
                if($result->count()>0){
                    foreach ($result->items() as $r){
                        if($r->goods_img!=null&&$r->goods_img!=''){
                            $r->goods_img=explode(',',$r->goods_img);
                        }else{
                            $r->goods_img=array();
                        }

                        //确定每个商品的价格，则以规格表的最低价格为准
                        $spec=PtGoodsSpec::where('goods_id',$r->id)->select('price')->orderBy('price','asc')->first();
                        $r->price=0;
                        if($spec!=null){
                            $r->price=$spec->price;
                        }
                        //计算每个商品的销量
                        $count=$this->getGoodsSaleStat($r->id,$supp_id);
                        $r->sale_num=$count;
                        $r->checked=false;//前端需要的参数
                        $r->background='#ffffff';//前端需要的参数
                    }
                }else{
                    return null;
                }
            }else{
                return null;
            }

            return $result;
        }catch (Exception $ex) {
            Log::error(get_class($this).' exception '.print_r($ex->getMessage(), true));
            throw $ex;
        }
    }


    //根据库商品ID和供应商id统计商品的销量
    public function getGoodsSaleStat($goods_id,$supp_id){
        try {
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'start');
            $count=PtGoodsOrderMid::where(['goods_id'=>$goods_id,'supp_id'=>$supp_id])
                ->whereNotIn('status',[0,1])
                ->sum('num');
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
            return $count;
        }catch (Exception $ex) {
            Log::error(get_class($this).' exception '.print_r($ex->getMessage(), true));
            throw $ex;
        }
    }


    //获取商品分组列表数据
    public function readGoodsGroupList($supp_id){
        try{
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'start');

            $result=PtSuppGoodsGroup::where('pt_supp_goods_group.supp_id',$supp_id)->where('is_online',0)
                ->select('shop_goods_group.id as value','shop_goods_group.name','shop_goods_group.seq')
                ->leftJoin('shop_goods_group','shop_goods_group.id','=','pt_supp_goods_group.group_id')
                ->orderBy('seq','asc')->get();
            if(!empty($result)){
                foreach ($result as $r){
                    $goods_ids=PtGoods::where('supp_id',$supp_id)->pluck('id')->all();
                    $group_goods_ids=ShopGoodsGroupMid::where('group_id',$r->value)->pluck('goods_id')->all();
                    $ids=array();
                    if($group_goods_ids!=null&&count($group_goods_ids)>0){
                        foreach ($group_goods_ids as $gid){
                            if(in_array($gid,$goods_ids)){
                                $ids[]=$gid;
                            }
                        }
                    }
                    $r->goods_num=count($ids);
                    $r->checked=false;

                }
            }

            Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
            return  $result;
        }catch (Exception $ex) {
            Log::error(get_class($this).' exception '.print_r($ex->getMessage(), true));
            throw $ex;
        }
    }



    //添加商品
    public function addGoods($goods,$group,$supp_id){
        try{
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'start');
            DB::beginTransaction();
            $goods['online']=1;
            $goods['total_stock_num']=0;
            $result=PtGoods::create($goods);
            if(count($group)>0){
                $id=$result->id;
                foreach ($group as $g){
                    ShopGoodsGroupMid::create(['group_id'=>$g,'goods_id'=>$id]);
                }
            }
            DB::commit();
            return $result;
        }catch (Exception $ex) {
            DB::rollBack();
            Log::error(get_class($this).' exception '.print_r($ex->getMessage(), true));
            throw $ex;
        }
    }


    //更新商品信息
    public function updateGoodsMsg($goods,$group){
        try{
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'start');
            DB::beginTransaction();
            if(!array_key_exists('id',$goods)){
                DB::rollBack();
                Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
                return ['code'=>-1];
            }
            PtGoods::where('id',$goods['id'])->update($goods);
            if(count($group)>0){
                $id=$goods['id'];
                ShopGoodsGroupMid::where('goods_id',$id)->delete();
                foreach ($group as $g){
                    //查询商品所有分组
                    if(!empty($g)){
                        ShopGoodsGroupMid::create(['group_id'=>$g,'goods_id'=>$id]);
                    }

                }
            }
            DB::commit();
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
            return ['code'=>1];
        }catch (Exception $ex) {
            DB::rollBack();
            Log::error(get_class($this).' exception '.print_r($ex->getMessage(), true));
            throw $ex;
        }
    }


    //查看商品详情
    public function readGoodsById($id,$supp_id){
        try{
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'start');
            $result=PtGoods::where(['id'=>$id,'creator_ownto_id'=>$supp_id])->first();

            //查询字典表
            $params['send_type']='商品配送方式';
            $params['online']='通用是否';
            $params['is_combine']='通用是否';
            $params['category_id']='商品品类';
            $params['is_food']='通用是否';
            $params['is_new']='通用是否';
            $params['goods_type']='平台发布商品类型';
            $params['pre_sale']='通用是否';
            $dict=DictUtils::getDictMsg($params);

            //查询商品的分组信息
            $group_ids=ShopGoodsGroupMid::where('goods_id',$id)->pluck('group_id')->all();
            if($group_ids==null){
                $group_ids=array();
            }

            Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
            return  ['res'=>$result,'dict'=>$dict,'group'=>$group_ids];
        }catch (Exception $ex) {
            Log::error(get_class($this).' exception '.print_r($ex->getMessage(), true));
            throw $ex;
        }
    }


    //删除商品
    public function delectGoodsByIds($del_ids,$supp_id){
        try{
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'start');
            DB::beginTransaction();
            if($del_ids!=null&&count($del_ids)>0){

            }
            //先查询商品的状态是否是已下线
            $goods_list=PtGoods::whereIn('id',$del_ids)->where('supp_id',$supp_id)->get();
            $goods_ids=array();
            if($goods_list!=null&&count($goods_list)>0){
                foreach ($goods_list as $g){
                    if($g->online==0){
                        $goods_ids[]=$g->id;
                    }
                }
            }
            if($goods_ids!=null&&count($goods_ids)>0){
                return ['code'=>-1,'data'=>$goods_ids];
            }

            //删除商品
            PtGoods::whereIn('id',$del_ids)->where('supp_id',$supp_id)->delete();

            DB::commit();
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
            return ['code'=>1];
        }catch (Exception $ex) {
            DB::rollBack();
            Log::error(get_class($this).' exception '.print_r($ex->getMessage(), true));
            throw $ex;
        }
    }




    //商品上架或下架
    public function goodsOnlineOrDownline($supp_id,$dis,$type){
        try{
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'start');
            DB::beginTransaction();
            Log::info($supp_id);
            Log::info($dis);
            Log::info($type);
            if(empty($dis)){
                DB::rollBack();
                Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
                return ['code'=>-1,'data'=>array()];
            }
            if($type==0){//上架
                //判断商品是否有规格
                $notHaveSpec=array();
                foreach ($dis as $id){
                    $count=PtGoodsSpec::where('goods_id',$id)->count();
                    if($count==0){
                        $notHaveSpec[]=$id;
                    }
                }
                if(count($notHaveSpec)>0){
                    return ['code'=>-1,'data'=>$notHaveSpec];
                }
                PtGoods::whereIn('id',$dis)->where('creator_ownto_id',$supp_id)->update(['online' => 0]);

            }
            if($type==1){//下架
                PtGoods::whereIn('id',$dis)->where('creator_ownto_id',$supp_id)->update(['online' => 1]);
            }

            DB::commit();
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
            return ['code'=>1];
        }catch (Exception $ex) {
            DB::rollBack();
            Log::error(get_class($this).' exception '.print_r($ex->getMessage(), true));
            throw $ex;
        }
    }


    //添加商品规格
    public function addSpec($spec){
        try{
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'start');
            DB::beginTransaction();
            if(!array_key_exists('supp_id',$spec)||!array_key_exists('goods_id',$spec)){
                return ['code'=>-1];
            }
            $spec['creator_ownto_id']=$spec['supp_id'];
            $spec['account_types']=1;
            $result=PtGoodsSpec::create($spec);
            //更新商品的总库存和最低价格
            $this->updateStockNumMinPrice($spec['goods_id']);
            DB::commit();
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
            return ['code'=>1,'data'=>$result];
        }catch (Exception $ex) {
            DB::rollBack();
            Log::error(get_class($this).' exception '.print_r($ex->getMessage(), true));
            throw $ex;
        }
    }


    //更新商品规格
    public function updateGoodsSpecMsg($spec){
        try{
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'start');
            DB::beginTransaction();
            if(!array_key_exists('id',$spec)||!array_key_exists('supp_id',$spec)||!array_key_exists('goods_id',$spec)){
                return ['code'=>-1];
            }
            PtGoodsSpec::updateOrCreate(['id'=>$spec['id']],$spec);
            //更新商品的总库存
            $this->updateStockNumMinPrice($spec['goods_id']);
            DB::commit();
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
            return ['code'=>1];
        }catch (Exception $ex) {
            DB::rollBack();
            Log::error(get_class($this).' exception '.print_r($ex->getMessage(), true));
            throw $ex;
        }
    }

    //更新商品的总库存
    public function updateStockNumMinPrice($goods_id){
        try{
            //更新商品的总库存
            $stock_num=PtGoodsSpec::where('goods_id',$goods_id)->sum('stock_num');
            $min_price=PtGoodsSpec::where('goods_id',$goods_id)->min('price');
            $goods=PtGoods::find($goods_id);
            if($goods!=null){
                $goods->total_stock_num=$stock_num;
                if($min_price!=null){
                    $goods->min_price=$min_price;
                }
                $goods->save();
            }
        }catch (Exception $ex) {
            DB::rollBack();
            Log::error(get_class($this).' exception '.print_r($ex->getMessage(), true));
            throw $ex;
        }
    }


    //查看商品详情
    public function readSpecById($id,$supp_id){
        try{
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'start');
            $result=PtGoodsSpec::where(['id'=>$id,'supp_id'=>$supp_id])->first();
            //查询字典表
            $params['is_online']='通用是否';
            $dict=DictUtils::getDictMsg($params);
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
            return  ['res'=>$result,'dict'=>$dict];
        }catch (Exception $ex) {
            Log::error(get_class($this).' exception '.print_r($ex->getMessage(), true));
            throw $ex;
        }
    }


    //删除商品规格
    public function deleteGoodsSpecMsg($del_ids,$supp_id,$goods_id){
        try{
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'start');
            DB::beginTransaction();

            //2、商品下架期间，该商品的所有状态规格都可以删除
            //先查询商品的状态是否是已下线
            $pgoods=PtGoods::where(['id'=>$goods_id,'creator_ownto_id'=>$supp_id,'account_types'=>1])->first();
            $goods_spec_list=PtGoodsSpec::whereIn('pt_goods_spec.id',$del_ids)->where('pt_goods_spec.creator_ownto_id',$supp_id)
                ->select('pt_goods_spec.id','pt_goods_spec.is_online')
                ->get();
            $spec_ids=array();
            if($pgoods!=null){
                if($pgoods->online==0){
                    //1、商品上架期间，仅下架规格可删
                    foreach ($goods_spec_list as $g){
                        if($g->is_online==0){
                            $spec_ids[]=$g->id;
                        }
                    }
                }
            }
            if($spec_ids!=null&&count($spec_ids)>0){
                return ['code'=>-1,'data'=>$spec_ids];
            }

            //删除规格
            PtGoodsSpec::whereIn('id',$del_ids)->where('supp_id',$supp_id)->delete();
            DB::commit();
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
            return ['code'=>1];
        }catch (Exception $ex) {
            DB::rollBack();
            Log::error(get_class($this).' exception '.print_r($ex->getMessage(), true));
            throw $ex;
        }
    }



    //查看商品的所有规格
    public function readAllGoodsSpec($id,$supp_id){
        try{
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'start');
            $result=PtGoodsSpec::where(['goods_id'=>$id,'supp_id'=>$supp_id])->get();
            //查询字典表
            $params['is_online']='通用是否';
            $dict=DictUtils::getDictMsg($params);
            if($result!=null&&count($result)>0){
                foreach ($result as $r){
                    $r->checked=false;
                    $r->background='#ffffff';
                }
            }

            Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
            return  ['res'=>$result,'dict'=>$dict];
        }catch (Exception $ex) {
            Log::error(get_class($this).' exception '.print_r($ex->getMessage(), true));
            throw $ex;
        }
    }



    //商品规格上架或下架
    public function specOnlineOrDownline($supp_id,$ids,$type,$goods_id){
        try{
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'start');
            DB::beginTransaction();
            if(empty($ids)){
                DB::rollBack();
                Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
                return ['code'=>-1];
            }
            if($type==0){//上架
                PtGoodsSpec::whereIn('id',$ids)->where('supp_id',$supp_id)->update(['is_online' => 0]);

            }
            if($type==1){//下架
                PtGoodsSpec::whereIn('id',$ids)->where('supp_id',$supp_id)->update(['is_online' => 1]);
                //当规格全部下线的时候，自动把这个商品下线
                $count=PtGoodsSpec::where(['goods_id'=>$goods_id,'is_online'=>0])->count();
                if($count==0){
                    //下架商品
                    PtGoods::where('id',$goods_id)->update(['online'=>1]);
                }

            }

            DB::commit();
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
            return ['code'=>1];
        }catch (Exception $ex) {
            DB::rollBack();
            Log::error(get_class($this).' exception '.print_r($ex->getMessage(), true));
            throw $ex;
        }
    }

}